//
//  AppDelegate.m
//  MemberBusiness-ios
//
//  Created by cherry pu on 2018/4/18.
//  Copyright © 2018年 zhangXin. All rights reserved.
//

#import "AppDelegate.h"
#import "MBTabbarController.h"
#import "MBLoginViewController.h"
#import <UMCommon/UMCommon.h>
#import <UMPush/UMessage.h>             // Push组件
#import <UserNotifications/UserNotifications.h>


@interface AppDelegate ()<UNUserNotificationCenterDelegate>

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(pushLoginVC) name:NOTIFICATION_LOGIN_SHOW_VIEW object:nil];
    
    int cacheSizeMemory = 4*1024*1024; // 4MB
    int cacheSizeDisk = 32*1024*1024; // 32MB
    NSURLCache *sharedCache = [[NSURLCache alloc] initWithMemoryCapacity:cacheSizeMemory diskCapacity:cacheSizeDisk diskPath:@"nsurlcache"];
    [NSURLCache setSharedURLCache:sharedCache];
    
    [UITextView appearance].tintColor = COLOR_MAIN;
    [UITextField appearance].tintColor = COLOR_MAIN;
    
    //    友盟
    [UMConfigure setLogEnabled:YES];
    [UMessage openDebugMode:YES];

    [UMConfigure initWithAppkey:@"5ae28d46f43e4823f7000052" channel:@"App Store"];
    UMessageRegisterEntity * entity = [[UMessageRegisterEntity alloc] init];
    //type是对推送的几个参数的选择，可以选择一个或者多个。默认是三个全部打开，即：声音，弹窗，角标等
    entity.types = UMessageAuthorizationOptionBadge|UMessageAuthorizationOptionAlert;
    if (@available(iOS 10.0, *)) {
        [UNUserNotificationCenter currentNotificationCenter].delegate = self;
        [UMessage registerForRemoteNotificationsWithLaunchOptions:launchOptions Entity:entity completionHandler:^(BOOL granted, NSError * _Nullable error) {
            if (granted) {
                // 用户选择了接收Push消息
            }else{
                // 用户拒绝接收Push消息
            }
        }];
    }else {
        UIUserNotificationType types = UIUserNotificationTypeAlert |
        UIUserNotificationTypeBadge |
        UIUserNotificationTypeSound;
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:types categories:nil];
        
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
        [[UIApplication sharedApplication] registerForRemoteNotifications];
    }

    
    MBLoginUserModel* userModel = [MBLoginUserModelArchieveTool userInfoUnAchieveFromFile];
    if (userModel.token && ![userModel.token isEqualToString:@""]) {
        [UMessage addAlias:[NSString stringWithFormat:@"%ld",(long)userModel.user_id] type:[NSString stringWithFormat:@"%ld",(long)userModel.user_id] response:^(id  _Nonnull responseObject, NSError * _Nonnull error) {
            
        }];

        MBTabbarController* tabbarController = [[MBTabbarController alloc]init];
        self.window.rootViewController = tabbarController;

    }else {
        MBLoginViewModel* viewModel = [[MBLoginViewModel alloc]init];
        MBLoginViewController* loginVC = [[MBLoginViewController alloc]initWithViewModel:viewModel];
        self.window.rootViewController = loginVC;
    }
    [self.window makeKeyWindow];

    return YES;
}

-(void)pushLoginVC
{
    MBLoginUserModel* userModel = [MBLoginUserModelArchieveTool userInfoUnAchieveFromFile];
    [UMessage removeAlias:[NSString stringWithFormat:@"%ld",(long)userModel.user_id] type:[NSString stringWithFormat:@"%ld",(long)userModel.user_id] response:^(id  _Nonnull responseObject, NSError * _Nonnull error) {
        
    }];
    [MBLoginUserModelArchieveTool removeSelfUserFromDisk];

    MBLoginViewModel* viewModel = [[MBLoginViewModel alloc]init];
    MBLoginViewController* loginVC = [[MBLoginViewController alloc]initWithViewModel:viewModel];
    self.window.rootViewController = loginVC;
}


-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    
    NSString * StrDevice=[NSString stringWithFormat:@"%@",[[[[deviceToken description] stringByReplacingOccurrencesOfString: @"<" withString: @""]
                                                            stringByReplacingOccurrencesOfString: @">" withString: @""]
                                                           stringByReplacingOccurrencesOfString: @" " withString: @""]];
    [UMessage registerDeviceToken:deviceToken];
    [[NSUserDefaults standardUserDefaults] setObject:StrDevice forKey:@"deviceToken"];
    NSLog(@"%@",StrDevice);
    [[NSUserDefaults standardUserDefaults] synchronize];
    
}

//iOS10以下使用这两个方法接收通知，
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
    [UMessage setAutoAlert:NO];
    if([[[UIDevice currentDevice] systemVersion]intValue] < 10){
        [UMessage didReceiveRemoteNotification:userInfo];
        
        completionHandler(UIBackgroundFetchResultNewData);
    }
}

//iOS10新增：处理前台收到通知的代理方法
-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler NS_AVAILABLE_IOS(10_0){
    NSDictionary * userInfo = notification.request.content.userInfo;
    if (@available(iOS 10.0, *)) {
        if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
            //应用处于前台时的远程推送接受
            //关闭U-Push自带的弹出框
            [UMessage setAutoAlert:NO];
            //必须加这句代码
            [UMessage didReceiveRemoteNotification:userInfo];
            
        }else{
            //应用处于前台时的本地推送接受
        }
    } else {
        // Fallback on earlier versions
    }
    //当应用处于前台时提示设置，需要哪个可以设置哪一个
    if (@available(iOS 10.0, *)) {
        completionHandler(UNNotificationPresentationOptionSound|UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionAlert);
    } else {
        // Fallback on earlier versions
    }
    
}

//iOS10新增：处理后台点击通知的代理方法
-(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler NS_AVAILABLE_IOS(10_0){
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    if (@available(iOS 10.0, *)) {
        if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
            //应用处于后台时的远程推送接受
            //必须加这句代码
            [UMessage didReceiveRemoteNotification:userInfo];
            
        }else{
            //应用处于后台时的本地推送接受
        }
    } else {
        // Fallback on earlier versions
    }
}


@end
